package com.zmn.plat.admin.controller.contract.record;

import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.DictModel;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.excel.ExportExcel;
import com.zmn.common.utils.pager.LayuiPageUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.cas.web.StaffAdminService;
import com.zmn.mcc.common.dto.staff.StaffDRO;
import com.zmn.plat.common.constant.CompanyConsts;
import com.zmn.plat.common.dictionary.ContractFileTypeEnum;
import com.zmn.plat.common.dictionary.ContractPaymentStatusEnum;
import com.zmn.plat.common.dictionary.ContractStatusEnum;
import com.zmn.plat.common.dictionary.ContractTypeEnum;
import com.zmn.plat.model.entity.company.CompanyTypeQuery;
import com.zmn.plat.model.entity.contract.file.record.ContractFileRecord;
import com.zmn.plat.model.entity.contract.file.record.ContractFileRecordQuery;
import com.zmn.plat.model.entity.contract.record.ContractRecord;
import com.zmn.plat.model.entity.contract.record.ContractRecordQuery;
import com.zmn.plat.model.vo.contract.record.ContractRecordExportExcelVO;
import com.zmn.plat.model.vo.contract.record.ContractRecordVO;

/**
 * 合同表
 *
 * @author linfeng
 * @since 2020-05-09 11:41:45
 */
@Controller
@RequestMapping("/contract/record/")
public class ContractRecordListController extends ContractRecordBaseController {

    /**
     * 列表
     *
     * @param query
     * @author linfeng
     * @since 2020-05-09 11:41:45
     */
    @RequestMapping("list")
    @RequiresPermissions("/contract/record/list.action")
    public ModelAndView list(@ModelAttribute ContractRecordQuery query) {

        // 格式化时间选择器时间
        if (!StringUtil.isBlank(query.getSignBeginAndEndDay())) {
            String[] strings = LayuiPageUtil.dateIntercept(query.getSignBeginAndEndDay());
            query.setSignBeginDay(DateUtil.getDateStart(DateUtil.parse(strings[0], DateUtil.FORMAT_DATE)));
            query.setSignEndDay(DateUtil.getDateEnd(strings[1], DateUtil.FORMAT_DATE));
        }

        List<ContractRecordVO> items = contractRecordService.listPageByQuery(query);
        items.forEach(e -> {
            e.setSubjectAmountYuan(narrow(e.getSubjectAmount()));
        });

        List<CompanyTypeQuery> companyTypeList =
            Arrays.asList(new CompanyTypeQuery(CompanyConsts.COMPANY_TYPE_SUBSIDIARY, CompanyConsts.COMPANY_TYPE_CHILD_DEFAULT),
                new CompanyTypeQuery(CompanyConsts.COMPANY_TYPE_HEADOFFICE, CompanyConsts.COMPANY_TYPE_CHILD_DEFAULT));
        List<DictModel> companys = baseCompanyService.listByTypes(companyTypeList, null);

        Map<Integer, List<ContractFileRecord>> contractFileRecordMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(items)) {
            ContractFileRecordQuery contractFileRecordQuery = new ContractFileRecordQuery();
            contractFileRecordQuery.setContractIds(items.stream().map(e -> e.getContractId()).collect(Collectors.toList()));
            contractFileRecordMap = contractFileRecordService.listByQuery(contractFileRecordQuery).stream()
                .collect(Collectors.groupingBy(ContractFileRecord::getContractId));
        }

        boolean showExportExcel = StaffAdminService.isPermitted("/contract/record/exportExcel.action");

        ModelAndView mav = new ModelAndView("contract/record/list");
        mav.addObject("items", items);
        mav.addObject("contractFileRecordMap", contractFileRecordMap);
        mav.addObject("contractStatusList", ContractStatusEnum.values());
        mav.addObject("contractTypes", ContractTypeEnum.values());
        mav.addObject("contractPaymentStatusList", ContractPaymentStatusEnum.values());
        mav.addObject("companys", companys);
        mav.addObject("oneDepts", getOneDeptList());
        mav.addObject("twoDepts", getTwoDeptList());
        mav.addObject("vo", query);
        mav.addObject("showExportExcel", showExportExcel);
        return mav;
    }

    /**
     * 详情
     *
     * @param contractId
     * @author linfeng
     * @since 2020-05-09 11:41:45
     */
    @RequestMapping("detail")
    @RequiresPermissions("/contract/record/detail.action")
    public ModelAndView detail(@RequestParam(value = "contractId", defaultValue = "0") Integer contractId) {
        ContractRecord contractRecord;
        if (contractId == 0) {
            contractRecord = new ContractRecord();
        } else {
            contractRecord = contractRecordService.findByKey(contractId);
        }

        List<CompanyTypeQuery> companyTypeList =
            Arrays.asList(new CompanyTypeQuery(CompanyConsts.COMPANY_TYPE_SUBSIDIARY, CompanyConsts.COMPANY_TYPE_CHILD_DEFAULT),
                new CompanyTypeQuery(CompanyConsts.COMPANY_TYPE_HEADOFFICE, CompanyConsts.COMPANY_TYPE_CHILD_DEFAULT));
        List<DictModel> companys = baseCompanyService.listByTypes(companyTypeList, null);
        ContractRecordVO contractRecordVO = new ContractRecordVO();
        BeanUtils.copyProperties(contractRecord, contractRecordVO);
        List<Integer> alertStaffIds = getAgentAndAlertReceiverStaffIds(contractRecord);
        List<StaffDRO> alertStaffs = new ArrayList<>();
        if (!CollectionUtils.isEmpty(alertStaffIds)) {
            ResponseDTO<List<StaffDRO>> data = staffListRemoteService.listStaffByStaffIds(alertStaffIds, GlobalConsts.YES);
            if (data.isSuccess()) {
                alertStaffs = data.getData();
            }
        }

        Map<Integer, StaffDRO> alertStaffMap = alertStaffs.stream().collect(Collectors.toMap(e -> e.getStaffId(), e -> e));
        contractRecordVO.setStaffMap(alertStaffMap);
        contractRecordVO.setSubjectAmountYuan(narrow(contractRecordVO.getSubjectAmount()));

        List<ContractFileRecord> contractScanCopys = new ArrayList<>();
        List<ContractFileRecord> sonContracts = new ArrayList<>();
        if (NumberUtil.isNotNullOrZero(contractId)) {
            ContractFileRecordQuery contractFileRecordQuery = new ContractFileRecordQuery();
            contractFileRecordQuery.setContractId(contractId);
            contractFileRecordQuery.setFileType(ContractFileTypeEnum.CONTRACTSCANCOPY.getCode());
            contractScanCopys = contractFileRecordService.listByQuery(contractFileRecordQuery);

            contractFileRecordQuery.setFileType(ContractFileTypeEnum.SONCONTRACT.getCode());
            sonContracts = contractFileRecordService.listByQuery(contractFileRecordQuery);
        }

        ModelAndView mav = new ModelAndView("contract/record/detail");
        mav.addObject("obj", contractRecordVO);
        mav.addObject("contractStatusList", ContractStatusEnum.values());
        mav.addObject("companys", companys);
        mav.addObject("oneDepts", getOneDeptList());
        mav.addObject("twoDepts", getTwoDeptList());
        mav.addObject("contractTypes", ContractTypeEnum.values());
        mav.addObject("contractScanCopys", contractScanCopys);
        mav.addObject("sonContracts", sonContracts);
        mav.addObject("flag", 1);
        return mav;
    }

    @RequestMapping(value = "exportExcel")
    @RequiresPermissions("/contract/record/exportExcel.action")
    public void exportExcel(HttpServletResponse response, ContractRecordQuery query) {
        Integer pageSize = getExportPageLimit(response);
        query.setPageSize(pageSize);

        try {
            ExportExcel<ContractRecordExportExcelVO> excel = contractRecordBService.exportExcel(query, getMcStaff());
            excel.exportExcel(response, "合同管理列表");
        } catch (Exception e) {
            logger.error("导出报表出错" + e.getMessage(), e);
        }
    }

    @RequestMapping(value = "downLoad")
    @RequiresPermissions("/contract/borrow/record/addEdit.action")
    public void downLoadFile(HttpServletResponse response, String file) {
        contractRecordBService.downLoadFile(response, file);
    }

    @RequestMapping(value = "listCompanys")
    public void listCompanys(HttpServletResponse response, @RequestParam(value = "staffId", defaultValue = "1") int staffId) {
        super.listCompanys(response, staffId);
    }

    @RequestMapping(value = "getStaff")
    @ResponseBody
    public ResponseDTO getStaff(Integer staffId) {
        ResponseDTO<StaffDRO> data = staffListRemoteService.getStaff(staffId);
        StaffDRO staff = new StaffDRO();
        if (data.isSuccess()) {
            staff = data.getData();
        }

        return ResponseDTO.success(staff);
    }
}
